/**
 * created by dqn 2018/3/8 21:14
 */

package main.controller;

import main.util.MD5Util;
import main.util.Paths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class DataController {
    @Autowired
    MD5Util md5Util;

    @RequestMapping(value = "/song/data", method = RequestMethod.GET)
    public void responDatas(HttpServletRequest httpServletRequest,
                            HttpServletResponse httpServletResponse,
                            @RequestParam("file") String requestFile) {
        doRespon(httpServletRequest, httpServletResponse, requestFile);
    }

    public void doRespon(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String requestFile) {
        String filePath = Paths.UPLOAD_DIR + Paths.SONG_DIR + "/" + requestFile;
        File readFile = new File(filePath);
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(readFile);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedOutputStream = new BufferedOutputStream(httpServletResponse.getOutputStream());
            long start = 0;
            long total = bufferedInputStream.available();
            long end = total - 1;
            int bufferSize = 1024 * 1024;
            String rangeString = httpServletRequest.getHeader("range");
            if ((rangeString != null) && (!rangeString.equals(""))) {
                String[] range = rangeString.split("=")[1].split("-");
                start = Long.valueOf(range[0]);
                if (range.length > 1) {
                    end = Long.valueOf(range[1]);
                }
                httpServletResponse.setContentLength((int) (end - start + 1));
                httpServletResponse.addHeader("Status", 206 + "");
                httpServletResponse.addHeader("Accept-Ranges", "bytes");
                httpServletResponse.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + total);
            } else {
                httpServletResponse.setContentLength((int) total);
            }
            httpServletResponse.setContentType("audio/mpeg");
            httpServletResponse.addHeader("Etag",md5Util.getEncodedMD5(filePath));

            long pos = start;
            System.out.println(pos);
            byte[] buffer = new byte[bufferSize];
            bufferedInputStream.skip(pos);
            int readSize = bufferedInputStream.read(buffer);
            while (readSize != -1 && pos <= end) {
                System.out.println("writing -->" + readSize + "bytes,pos: " + pos + ",end with: " + end + ",start with: " + start);
                bufferedOutputStream.write(buffer, 0, readSize);
                bufferedOutputStream.flush();
                pos += readSize;
                readSize = bufferedInputStream.read(buffer);
            }
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
//        int size = 1024 * 1024 * 200;
//        byte[] buffer = new byte[size];
//        try {
//            fileInputStream = new FileInputStream(readFile);
//            int readSize =  fileInputStream.read(buffer);
//            bufferedOutputStream = new BufferedOutputStream(httpServletResponse.getOutputStream());
//            String rangeString = httpServletRequest.getHeader("range");
//            long start = 0;
//            long total = readSize;
//            long end = total - 1;
//            if (rangeString!=null && !rangeString.equals("")){
//                String[] ranges = rangeString.split("=")[1].split("-");
//               start = Long.valueOf(ranges[0]);
//               if (ranges.length > 1){
//                   end = Long.valueOf(ranges[1]);
//               }
//                httpServletResponse.setContentLength((int) (end - start + 1));
//                httpServletResponse.addHeader("Status", 206 + "");
//                httpServletResponse.addHeader("Accept-Ranges", "bytes");
//                httpServletResponse.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + total);
//            }else {
//                httpServletResponse.setContentLength((int) total);
//            }
////            httpServletResponse.setContentType("audio/mpeg");
//            httpServletResponse.setContentType("application/octet-stream");
//            if (start == 0){
//                start = 1;
//            }
//            bufferedOutputStream.write(buffer,(int)start-1,(int)end+1);
//            bufferedOutputStream.flush();
//            bufferedOutputStream.close();
//            fileInputStream.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//            try {
//                fileInputStream.close();
//                bufferedOutputStream.close();
//                doRespon(httpServletRequest,httpServletResponse,requestFile);
//            } catch (IOException e1) {
//                e1.printStackTrace();
//            }
//        }

    }


    @RequestMapping(value = "/song/image", method = RequestMethod.GET)
    public void responseImage(HttpServletRequest httpServletRequest,
                              HttpServletResponse httpServletResponse,
                              @RequestParam("file") String requestFile) {
        File file = new File(Paths.UPLOAD_DIR + Paths.IMAGE_DIR + "/" + requestFile);
        try {
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(httpServletResponse.getOutputStream());
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[1024];
            int readSize = bufferedInputStream.read(buffer);
            while (readSize != -1) {
                bufferedOutputStream.write(buffer, 0, readSize);
                readSize = bufferedInputStream.read(buffer);
            }
            bufferedOutputStream.flush();
            bufferedInputStream.close();
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

